"""
=============
ballista.util
=============

Various simple (but far from useless!) utilities.

"""

import Cookie
import os
import time

def rfc3339(resource=None):
    """
    rfc3339
    =======

    rfc3339(resource=None) -> string
    Generate a RFC 3339-compliant timestamp from the sent ``resource`` (default is *now*).
    
    """
    format = '%Y-%m-%dT%H:%M:%S'
    if resource:
        out = time.strftime(format, resource)
    else:
        out = time.strftime(format)

    return out + tz_from_secs(-time.timezone)

def pieces(sequence, size):
    """
    pieces
    ======

    pieces(sequence, size)
    Split the sent ``sequence`` into pieces of length ``size``.
    
    """
    return [sequence[x:x + size] for x in range(0, len(sequence), size)]

def tz_from_secs(secs):
    """
    tz_from_secs
    ============

    tz_from_secs(secs) -> string
    Get a RFC 3339-compatible timezone offset (in relation to UTC) from an offset in seconds.
    
    """
    if secs == 0:
        return 'Z'

    sign = secs > 0 and '+' or '-'
    if secs < 0:
        secs = -secs
        sign = '-'
    else:
        sign = '+'

    hours = secs / 3600.
    return '%s%02d:%02d' % (sign, int(hours), int((hours % 1) * 60))

class CookieSet(Cookie.SimpleCookie):
    """
    CookieSet
    =========

    A slightly modified ``Cookie.SimpleCookie`` subclass.
    
    """
    def headers(self):
        """
        CookiesSet.headers
        ==================

        headers(self) -> list
        Return a set of headers.
        
        """
        return [line.split(': ', 1) for line in str(self).splitlines()]
